#!/bin/sh

# action-dcadmin
#
# This file works in combination with monitor-dcadmin
# the monitor-dcadmin script runs the fileschanged program
# in the background and executes this script whenever a
# change is detected in the file dcdata (without md5).
#
# In this script we interpret the actions in the dcdata
# file and exectute the various functions to manage the
# domain (e.g. add, delete users and domain settings).
#
# Author: M.Post
# Last modified: 10 October 2011

WORKDIR=/var/www/dcadmin/dctmp
RESULTS=/tmp/dcadmin.results
LOGFILE=/tmp/dcadmin.log
LOG_ENABLED=1
DC_GROUP=domain
MIN_PW_LENGTH=6

# set these manually!
MAIN_USER="testuser"
DC_DIR=/home/testuser/domain


# --- script follows ---

# delete the .ready file if it exists
rm -f $RESULTS.ready > /dev/null 2>&1

# create a new .results file
cat /dev/null > $RESULTS

MD5=`head -n 1 $WORKDIR/dcdata`

WORKFILE=$WORKDIR/dcdata_$MD5

cp $WORKFILE /tmp/workfile.tmp

if test $LOG_ENABLED -eq 1
then
  echo "`date` change detected in dcdata file" >> $LOGFILE
  echo "MD5 = $MD5" >> $LOGFILE
fi


if test -f $WORKFILE
then
  ACTION=`head -n 1 $WORKFILE`

  if test $LOG_ENABLED -eq 1
  then
    echo "WORKFILE = $WORKFILE" >> $LOGFILE
    echo "ACTION = $ACTION" >> $LOGFILE
  fi


  # --- Begin: ADD DOMAIN USER ACCOUNT --- 
  # --- Begin: ADD DOMAIN USER ACCOUNT --- 
  # --- Begin: ADD DOMAIN USER ACCOUNT --- 

  if [ "$ACTION" = "adduser" ]
  then

    ADD_ACCOUNT_STATUS=0
    # status legend:
    # 0 - account creation incomplete but ok so far
    # 1 - account creation successful
    # 2 - error: could not create unix account
    # 3 - error: could not set unix password
    # 4 - error: could not create samba account
    # 5 - error: could not set samba password
    # 6 - error: could not create domain group

    VALIDATION_STATUS=0
    # status legend:
    # 0 - validation incomplete but ok so far
    # 1 - validated ok
    # 2 - error: username empty or contains spaces
    # 3 - error: username already exists
    # 4 - error: other username error
    # 5 - error: password empty
    # 6 - error: password too short
  

    DC_USER=`head -n 2 $WORKFILE | tail -n 1 | grep user | awk -F : '{print $2}'`
    DC_PASS=`head -n 3 $WORKFILE | tail -n 1 | grep pass | awk -F : '{print $2}'`


    # validate input fields

    # validate user name
    if test -z "$DC_USER"  
    then
      echo "Error: username empty" >> $RESULTS
      if test $LOG_ENABLED -eq 1
      then
        echo "Error: username empty" >> $LOGFILE
      fi

      VALIDATION_STATUS=2

    else

      if echo "$DC_USER" | grep " "
      then
        echo "Error: username contains spaces" >> $RESULTS
        if test $LOG_ENABLED -eq 1
        then
          echo "Error: username contains spaces" >> $LOGFILE
        fi
        VALIDATION_STATUS=2

      else

        # test if user account already exists
       
        if cat /etc/passwd | awk -F : '{print $1}' | grep ^$DC_USER$ > /dev/null
        then

          echo "Error: username already exists" >> $RESULTS
          if test $LOG_ENABLED -eq 1
          then
            echo "Error: username already exists" >> $LOGFILE
          fi
          VALIDATION_STATUS=3

        else
          if test $LOG_ENABLED -eq 1
          then
            echo "Username validation: passed" >> $LOGFILE
          fi

        fi 

      fi

    fi

 
    if test $VALIDATION_STATUS -eq 0 
    then

      # validate password
      if test -z "$DC_PASS" 
      then
        echo "Error: password empty" >> $RESULTS
        if test $LOG_ENABLED -eq 1
        then
          echo "Error: password empty" >> $LOGFILE
        fi
        VALIDATION_STATUS=5

      else
      
        # test password length

        PWLEN=${#DC_PASS}

        if test $PWLEN -lt $MIN_PW_LENGTH
        then
          echo "Error: password too short, 6 chars min" >> $RESULTS

          if test $LOG_ENABLED -eq 1
          then
            echo "Error: password too short, 6 chars min" >> $LOGFILE
          fi
          VALIDATION_STATUS=6 

        else
          if test $LOG_ENABLED -eq 1
          then
            echo "Password validation: passed" >> $LOGFILE
          fi
          VALIDATION_STATUS=1

        fi 

      fi
    fi


    # validation process completed, proceeding with account creation 

    if test $VALIDATION_STATUS -eq 1
    then

      # input fields passed validation, proceed with creating account

      if test $LOG_ENABLED -eq 1
      then
        echo "Result: validation successful, proceeding with creating account" >> $LOGFILE

        echo "Adding user: $DC_USER" >> $LOGFILE
        # echo "Password: $DC_PASS" >> $LOGFILE
        echo "Password: (hidden)" >> $LOGFILE
      fi 


      # check if domain group exists. Create one if not present.

      if cat /etc/group | awk -F : '{print $1}' | grep ^$DC_GROUP$ > /dev/null
      then

          if test $LOG_ENABLED -eq 1
          then
            echo "Using existing domain group: $DC_GROUP" >> $LOGFILE
          fi

      else

          # domain group doesn't exist, try to create one now

          if groupadd $DC_GROUP
          then
            echo "Created $DC_GROUP group: success" >> $RESULTS

            if test $LOG_ENABLED -eq 1
            then
              echo "Created $DC_GROUP group: success" >> $LOGFILE
            fi

          else

            echo "Created $DC_GROUP group: failed!" >> $RESULTS

            if test $LOG_ENABLED -eq 1
            then
              echo "Created $DC_GROUP group: failed!" >> $LOGFILE
            fi
            ADD_ACCOUNT_STATUS=6

          fi

      fi 


      if test $ADD_ACCOUNT_STATUS -eq 0
      then

        # create a new local unix user account

        if useradd $DC_USER -g $DC_GROUP -m
        then
          echo "Creating local Unix account: success" >> $RESULTS
          if test $LOG_ENABLED -eq 1
          then
            echo "Creating local Unix account: success" >> $LOGFILE
          fi 

          # set unix password
          if echo $DC_USER:"$DC_PASS" | chpasswd 
          then
            echo "Setting unix password for account: success" >> $RESULTS
            if test $LOG_ENABLED -eq 1
            then
              echo "Setting unix password for account: success" >> $LOGFILE
            fi
          else
            echo "Setting unix password for account: failed" >> $RESULTS
            if test $LOG_ENABLED -eq 1
            then
              echo "Setting unix password for account: failed" >> $LOGFILE
            fi 
            ADD_ACCOUNT_STATUS=3
          fi
  
        else
          echo "Creating local Unix account: failed!" >> $RESULTS
          if test $LOG_ENABLED -eq 1
          then
            echo "Creating local Unix account: failed!" >> $LOGFILE
          fi
          ADD_ACCOUNT_STATUS=2

        fi
     
      fi
 
      # finished creating unix account, proceed with creating samba account

      if test $ADD_ACCOUNT_STATUS -eq 0
      then

        # proceed with creating samba account

        if (echo $DC_PASS; echo $DC_PASS) | smbpasswd -as $DC_USER > /dev/null
        then
          echo "Creating samba user: success" >> $RESULTS
          if test $LOG_ENABLED -eq 1
          then
            echo "Creating samba user: success" >> $LOGFILE
          fi
          ADD_ACCOUNT_STATUS=1

        else
          echo "Creating samba user: failed" >> $RESULTS
          if test $LOG_ENABLED -eq 1
          then
            echo "Creating samba user: failed" >> $LOGFILE
          fi
          ADD_ACCOUNT_STATUS=2

        fi

      else

        # account creation failed, throw error and exit
        echo "Result: account creation failed!" >> $RESULTS
        if test $LOG_ENABLED -eq 1
        then
          echo "Result: account creation failed!" >> $LOGFILE
        fi

      fi

    else
      
      # validation failed, throw error and exit
      echo "Result: validation failed, account not created" >> $RESULTS
      if test $LOG_ENABLED -eq 1
      then
        echo "Result: validation failed, account not created" >> $LOGFILE
      fi

    fi

  fi

  # --- End: ADD DOMAIN USER ACCOUNT --- 


  # --- Begin: MODIFY DOMAIN USER ACCOUNT --- 
  # --- Begin: MODIFY DOMAIN USER ACCOUNT --- 
  # --- Begin: MODIFY DOMAIN USER ACCOUNT --- 

  if [ "$ACTION" = "moduser" ]
  then
    
    USERMOD_ACTION=`head -n 2 $WORKFILE | tail -n 1 | grep action | awk -F : '{print $2}'`
 
    if test $LOG_ENABLED -eq 1
    then
      echo "modify user accounts selected" >> $LOGFILE 
    fi

 
    # --- Begin: SHOW ALL USER ACCOUNTS --- 
    # --- Begin: SHOW ALL USER ACCOUNTS --- 
    # --- Begin: SHOW ALL USER ACCOUNTS --- 

    if [ "$USERMOD_ACTION" = "show" ]
    then

      # get the gid for the group DC_GROUP

      DC_GROUP_GID=`getent group $DC_GROUP | cut -d: -f3`
      echo "<table border=1>" >> $RESULTS
      cat /etc/passwd | grep $DC_GROUP_GID | awk -F : '{print "<tr><td><a href=index.php?moduser=",$1}{print ">",$1,"</a></td></tr>"}' | sed s/=\ /=/ >> $RESULTS

      echo "</table>" >> $RESULTS

    fi

    # --- End: SHOW ALL USER ACCOUNTS --- 

    # --- Begin: RESET USER ACCOUNT PASSWORD --- 
    # --- Begin: RESET USER ACCOUNT PASSWORD --- 
    # --- Begin: RESET USER ACCOUNT PASSWORD --- 

    if [ "$USERMOD_ACTION" = "resetpw" ]
    then
 
      USERMOD_DATA=`head -n 3 $WORKFILE | tail -n 1 | grep user | awk -F : '{print $2}'`
      USERMOD_PW=`head -n 4 $WORKFILE | tail -n 1 | grep passwd | awk -F : '{print $2}'`
      
      # echo "Password: $USERMOD_PW" >> $RESULTS
      # check if user is part of dc_group

      # get all the groups the user is part of
      USER_GROUPS=`groups $USERMOD_DATA`

      # count the number of groups from the last command
      GROUPS_COUNT=`echo "$USER_GROUPS" | awk '{field = NF}; END {print field}'`

      # run through all groups to check if they are part of DC_GROUP
      VALIDATION_STATUS=0 
      FAIL_REASON="This account is not part of group: $DC_GROUP"
      COUNT=1
      while test $COUNT -le $GROUPS_COUNT
      do
       
        READ_GROUP=`echo $USER_GROUPS | awk 'BEGIN{a='$COUNT'}END{print $a}'`

        if [ "$READ_GROUP" == "$DC_GROUP" ]
        then
           VALIDATION_STATUS=1 
        fi 

        COUNT=$((COUNT + 1))

      done 


      # check if username is not reserved

      if [ "$USERMOD_DATA" = "Administrator" ] || [ "$USERMOD_DATA" = "root" ]
      then
        VALIDATION_STATUS=2
        FAIL_REASON="The $USERMOD_DATA account is a reserved account"
      fi

      # only proceed with changing the account password if ok to do so
      
      if test $VALIDATION_STATUS -eq 1
      then

        if (echo $USERMOD_PW; echo $USERMOD_PW) | smbpasswd -as $USERMOD_DATA > /dev/null
        then

          echo "Reset samba account password: ok" >> $RESULTS


          # reset local Linux password
          if echo $USERMOD_DATA:"$USERMOD_PW" | chpasswd 
          then

            echo "Reset local Linux account password: ok" >> $RESULTS

          else

            echo "Reset local Linux account password: failed" >> $RESULTS

          fi

        else

          echo "Reset samba account password: failed" >> $RESULTS

        fi


      else
        echo "Unable to reset account password for: $USERMOD_DATA" >> $RESULTS
        echo "$FAIL_REASON" >> $RESULTS
      fi

    fi

    # --- End: RESET USER ACCOUNT PASSWORD --- 


    # --- Begin: LOCK USER ACCOUNT --- 
    # --- Begin: LOCK USER ACCOUNT --- 
    # --- Begin: LOCK USER ACCOUNT --- 

    if [ "$USERMOD_ACTION" = "lock" ]
    then

      USERMOD_DATA=`head -n 3 $WORKFILE | tail -n 1 | grep user | awk -F : '{print $2}'`
      
      # check if user is part of dc_group

      # get all the groups the user is part of
      USER_GROUPS=`groups $USERMOD_DATA`

      # count the number of groups from the last command
      GROUPS_COUNT=`echo "$USER_GROUPS" | awk '{field = NF}; END {print field}'`

      # run through all groups to check if they are part of DC_GROUP
      VALIDATION_STATUS=0 
      FAIL_REASON="This account is not part of group: $DC_GROUP"
      COUNT=1
      while test $COUNT -le $GROUPS_COUNT
      do
       
        READ_GROUP=`echo $USER_GROUPS | awk 'BEGIN{a='$COUNT'}END{print $a}'`

        if [ "$READ_GROUP" == "$DC_GROUP" ]
        then
           VALIDATION_STATUS=1 
        fi 

        COUNT=$((COUNT + 1))

      done 


      # check if username is not reserved

      if [ "$USERMOD_DATA" = "Administrator" ] || [ "$USERMOD_DATA" = "$MAIN_USER" ] || [ "$USERMOD_DATA" = "root" ]
      then
        VALIDATION_STATUS=2
        FAIL_REASON="The $USERMOD_DATA account is a reserved account"
      fi


      # only proceed with locking account if ok to do so
      
      if test $VALIDATION_STATUS -eq 1
      then

        # lock smbpasswd account
        if smbpasswd -d $USERMOD_DATA > /dev/null 2>&1
        then
          echo "Disabling samba account: ok" >> $RESULTS

          # lock user account in /etc/passwd
          if passwd -l $USERMOD_DATA > /dev/null 2>&1
          then

            echo "Locking local Linux account: ok" >> $RESULTS

          else

            echo "Locking local Linux account: failed" >> $RESULTS

          fi

        else

          echo "Disabling samba account: failed" >> $RESULTS

        fi

      else
        echo "Unable to disable account: $USERMOD_DATA" >> $RESULTS
        echo "$FAIL_REASON" >> $RESULTS
      fi

    fi

    # --- End: LOCK USER ACCOUNT --- 

    # --- Begin: UNLOCK USER ACCOUNT --- 
    # --- Begin: UNLOCK USER ACCOUNT --- 
    # --- Begin: UNLOCK USER ACCOUNT --- 

    if [ "$USERMOD_ACTION" = "unlock" ]
    then
 

      USERMOD_DATA=`head -n 3 $WORKFILE | tail -n 1 | grep user | awk -F : '{print $2}'`
      
      
      # check if user is part of dc_group

      # get all the groups the user is part of
      USER_GROUPS=`groups $USERMOD_DATA`

      # count the number of groups from the last command
      GROUPS_COUNT=`echo "$USER_GROUPS" | awk '{field = NF}; END {print field}'`

      # run through all groups to check if they are part of DC_GROUP
      VALIDATION_STATUS=0 
      FAIL_REASON="This account is not part of group: $DC_GROUP"
      COUNT=1
      while test $COUNT -le $GROUPS_COUNT
      do
       
        READ_GROUP=`echo $USER_GROUPS | awk 'BEGIN{a='$COUNT'}END{print $a}'`

        if [ "$READ_GROUP" == "$DC_GROUP" ]
        then
           VALIDATION_STATUS=1 
        fi 

        COUNT=$((COUNT + 1))

      done 


      # check if username is not reserved

      if [ "$USERMOD_DATA" = "Administrator" ] || [ "$USERMOD_DATA" = "$MAIN_USER" ] || [ "$USERMOD_DATA" = "root" ]
      then
        VALIDATION_STATUS=2
        FAIL_REASON="The $USERMOD_DATA account is a reserved account"
      fi


      # only proceed with unlocking account if ok to do so
      
      if test $VALIDATION_STATUS -eq 1
      then

        # unlock smbpasswd account
        if smbpasswd -e $USERMOD_DATA > /dev/null 2>&1
        then
          echo "Enabling samba account: ok" >> $RESULTS

          # unlock user account in /etc/passwd
          if passwd -u $USERMOD_DATA > /dev/null 2>&1
          then

            echo "Unlocking local Linux account: ok" >> $RESULTS

          else

            echo "Unlocking local Linux account: failed" >> $RESULTS

          fi

        else

          echo "Enabling samba account: failed" >> $RESULTS

        fi

      else
        echo "Unable to enable account: $USERMOD_DATA" >> $RESULTS
        echo "$FAIL_REASON" >> $RESULTS
      fi

    fi

    # --- End: UNLOCK USER ACCOUNT --- 

    # --- Begin: DELETE USER ACCOUNT --- 
    # --- Begin: DELETE USER ACCOUNT --- 
    # --- Begin: DELETE USER ACCOUNT --- 

    if [ "$USERMOD_ACTION" = "delete" ]
    then


      USERMOD_DATA=`head -n 3 $WORKFILE | tail -n 1 | grep user | awk -F : '{print $2}'`
      
      
      # check if user is part of dc_group

      # get all the groups the user is part of
      USER_GROUPS=`groups $USERMOD_DATA`

      # count the number of groups from the last command
      GROUPS_COUNT=`echo "$USER_GROUPS" | awk '{field = NF}; END {print field}'`

      # run through all groups to check if they are part of DC_GROUP
      VALIDATION_STATUS=0 
      FAIL_REASON="This account is not part of group: $DC_GROUP"
      COUNT=1
      while test $COUNT -le $GROUPS_COUNT
      do
       
        READ_GROUP=`echo $USER_GROUPS | awk 'BEGIN{a='$COUNT'}END{print $a}'`

        if [ "$READ_GROUP" == "$DC_GROUP" ]
        then
           VALIDATION_STATUS=1 
        fi 

        COUNT=$((COUNT + 1))

      done 


      # check if username is not reserved

      if [ "$USERMOD_DATA" = "Administrator" ] || [ "$USERMOD_DATA" = "$MAIN_USER" ] || [ "$USERMOD_DATA" = "root" ]
      then
        VALIDATION_STATUS=2
        FAIL_REASON="The $USERMOD_DATA account is a reserved account"
      fi




      # only proceed with deletion if ok to do so
      
      if test $VALIDATION_STATUS -eq 1
      then

        # remove user from smbpasswd
        if smbpasswd -x $USERMOD_DATA > /dev/null 2>&1
        then
          echo "Deleting samba account: ok" >> $RESULTS

          # remove user from /etc/passwd
          if userdel -r $USERMOD_DATA > /dev/null 2>&1
          then

            echo "Deleting local Linux account: ok" >> $RESULTS

            # clean up directory share (move to Administrator dir)

            if ! test -d $DC_DIR
            then
              # create DC_DIR (domain system dir for main user)

              TIMESTAMP=`date +%Y-%m-%d_%H_%M_%S`
              TARGETDIR=$DC_DIR/deleted_profiles/$TIMESTAMP
              mkdir -p $TARGETDIR
            fi

            if test -d $TARGETDIR
            then
              # move old user profile dir to TARGETDIR

              if mv /home/samba/profiles/$USERMOD_DATA $TARGETDIR/
              then
                chown -R $MAIN_USER $DC_DIR
                echo "Moving old user profile dirs: ok" >> $RESULTS
              else
                echo "Moving old user profile dirs: failed" >> $RESULTS

              fi

            else
              # could not access/create TARGETDIR
              echo "Cleaning up old user dirs: failed" >> $RESULTS
 
            fi

          else

            echo "Deleting local Linux account: failed" >> $RESULTS

          fi

        else

          echo "Deleting samba account: failed" >> $RESULTS

        fi

      else
        echo "Unable to delete account: $USERMOD_DATA" >> $RESULTS
        echo "$FAIL_REASON" >> $RESULTS
      fi

    fi

    # --- End: DELETE USER ACCOUNT --- 

  fi

  # --- End: MODIFY DOMAIN USER ACCOUNT --- 

 
  rm -f $WORKDIR/dcdata_*

else

  echo "WORKFILE $WORKFILE not found" >> $RESULTS

  if test $LOG_ENABLED -eq 1
  then

    echo "WORKFILE $WORKFILE not found" >> $LOGFILE

  fi

fi


# create a .ready file as soon as the results file has 
# been provided with all the information we wish to pass
# on to the web browser.


touch $RESULTS.ready
chown www-data $RESULTS
chown www-data $RESULTS.ready

# That's all folks!
